package com.ndood.base.service;

import com.ndood.base.pojo.Label;
import com.ndood.base.dao.LabelDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A.1.13 标签服务类
 */
@Service
public class LabelService {

	@Autowired
	private LabelDao labelDao;

	@Autowired
	private IdWorker idWorker;

	/**
	 * A.1.14 查询全部标签
	 */
	public List<Label> findAll(){
		return labelDao.findAll();
	}

	/**
	 * A.1.15 根据ID查询标签
	 */
	public Label findById(String id){
		return labelDao.findById(id).get();
	}

	/**
	 * A.1.16 增加标签
	 */
	public void add(Label label){
		label.setId(idWorker.nextId()+"" );
		labelDao.save(label) ;
	}

	/**
	 * A.1.17 修改标签
	 */
	public void update(Label label){
		labelDao.save(label);
	}

	/**
	 * A.1.18 删除标签
	 */
	public void deleteById(String id){
		labelDao.deleteById(id);
	}

	/**
	 * A.2.1 构建查询条件
	 */
	private Specification<Label> createSpecification(Map searchMap) {
		return new Specification<Label>() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {

				List<Predicate> predicates=new ArrayList<>();//查询条件的集合
				if(searchMap!=null){
					if(searchMap.get("labelname")!=null && !"".equals(searchMap.get("labelname"))){
						predicates.add( cb.like( root.get("labelname").as(String.class), "%"+(String)searchMap.get("labelname")+"%"   )   );
					}
					if(searchMap.get("state")!=null && !"".equals(searchMap.get("state"))){
						predicates.add( cb.equal( root.get("state").as(String.class), (String)searchMap.get("state")  ) );
					}
					if(searchMap.get("recommend")!=null && !"".equals(searchMap.get("recommend"))){
						predicates.add( cb.equal( root.get("recommend").as(String.class), (String)searchMap.get("recommend")  ) );
					}
				}
				return cb.and( predicates.toArray(  new Predicate[ predicates.size()]  )  );
			}
		};
	}

	/**
	 * A.2.2 条件查询
	 */
	public List<Label> findSearch(Map searchMap){
		Specification specification=createSpecification(searchMap);
		return labelDao.findAll(specification);
	}

	/**
	 * A.2.4 带分页条件查询
	 */
	public Page<Label> findSearch(Map searchMap, int page, int size){
		Specification specification=createSpecification(searchMap);
		PageRequest pageRequest=PageRequest.of(page-1,size);
		return labelDao.findAll(specification,pageRequest);
	}

}

